//
//  EJSSelectGoodsSpecView.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/27.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSSelectGoodsSpecView.h"
#import "FlyCollectionViewAlignFlowLayout.h"
#import "EJSSpecCCell.h"
#import "EJSSelectSpceCollectionReusableHeaderView.h"
#import "EJSGoodsModel.h"

#import <UIView+BlocksKit.h>

typedef void (^completion)(EJSGoodsSkuModel *selectSkuModel);

@interface EJSSelectGoodsSpecView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
}

@property (weak, nonatomic) IBOutlet UIImageView *goodsImageView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *specInfoLabel;
@property (weak, nonatomic) IBOutlet UILabel *skuNumLabel;



@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) EJSGoodsModel *goodsModel;
@property (strong, nonatomic) NSMutableArray *selectSpcs;

@property (strong, nonatomic) EJSGoodsSkuModel *selectSkuModel;

@property (copy, nonatomic) completion completion;


@end

@implementation EJSSelectGoodsSpecView

+(void)showSelectGoodsSpecView:(EJSGoodsModel *)goodsModel completion:(void(^)(EJSGoodsSkuModel *selectSkuModel))completion;{
    EJSSelectGoodsSpecView *selectGoodsSpecView = [[UINib nibWithNibName:@"EJSSelectGoodsSpecView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    selectGoodsSpecView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    selectGoodsSpecView.goodsModel = goodsModel;
    selectGoodsSpecView.completion = completion;
    UIWindow *kewWindow = [EJSAppDelegate sharedAppDelegate].window;
    [kewWindow addSubview:selectGoodsSpecView];
}

- (void)awakeFromNib{
    [super awakeFromNib];
    FlyCollectionViewAlignFlowLayout *layout = [[FlyCollectionViewAlignFlowLayout alloc] initLayoutWithCollectionViewAlignType:FlyCollectionViewAlignLeft];
    layout.minimumLineSpacing = 20;
    layout.minimumInteritemSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(0, 25, 0, 25);
    [self.collectionView setCollectionViewLayout:layout];
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSSpecCCell" bundle:nil] forCellWithReuseIdentifier:@"EJSSpecCCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"EJSSelectSpceCollectionReusableHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EJSSelectSpceCollectionReusableHeaderView"];
}

- (void)setGoodsModel:(EJSGoodsModel *)goodsModel{
    _goodsModel = goodsModel;
    
    //init data
    [self checkCanSelectGoodsSpceModel];//检查所有可选的属性
    //检查是否有默认的规格
    if(_goodsModel.hasDefaultSku.integerValue == 1 && _goodsModel.skus.count > 0){
        self.selectSkuModel = _goodsModel.skus.firstObject;
    }
    //初始化选择规格的数组
    NSMutableArray *selectSpces = [NSMutableArray arrayWithCapacity:_goodsModel.specs.count];
    for(int index = 0; index < _goodsModel.specs.count; index ++){
        [selectSpces addObject:@""];
    }
    self.selectSpcs = selectSpces;
    
    //update ui
    [self.goodsImageView setImageWithUrl:_goodsModel.cover];
    self.priceLabel.text =  [NSString stringWithFormat:@"€ %@",_goodsModel.price];
    self.skuNumLabel.text = self.goodsModel.minToBuy;
    [self.collectionView reloadData];
}

- (void)setSelectSkuModel:(EJSGoodsSkuModel *)selectSkuModel{
    _selectSkuModel = selectSkuModel;
    if(_selectSkuModel){
        self.skuNumLabel.text = self.goodsModel.minToBuy;
        self.priceLabel.text =  [NSString stringWithFormat:@"€ %@",_selectSkuModel.price];
        self.specInfoLabel.text = _selectSkuModel.specInfo;
    }else{
        self.priceLabel.text =  [NSString stringWithFormat:@"€ %@",_goodsModel.price];
        self.skuNumLabel.text = self.goodsModel.minToBuy;
        self.specInfoLabel.text = @"";
    }
}



//检查所有可选的规格
- (void)checkCanSelectGoodsSpceModel{
    for (EJSGoodsSpecModel *goodsSpecModel in _goodsModel.specs) {
        for (EJSSpecModel *specModel in goodsSpecModel.specs) {
            specModel.specSelectStatus = -1;
            for (EJSGoodsSkuModel *skuModel in _goodsModel.skus){
                if([skuModel.specInfo containsString:[NSString stringWithFormat:@"%@:%@",goodsSpecModel.specName,specModel.value]]){
                    specModel.specSelectStatus = 0;
                    break;
                }
            }
            if([self.selectSpcs containsObject:specModel]){
                specModel.specSelectStatus = 1;
            }
        }
    }
    [self findSelectSku];
}



//查找当前选择的sku
- (void)findSelectSku{
    for (EJSGoodsSkuModel *skuModel in _goodsModel.skus){
        if([self checkSelectSkuModel:skuModel]){
            self.selectSkuModel = skuModel;
            return;
        }
    }
    self.selectSkuModel = nil;
}

- (BOOL)checkSelectSkuModel:(EJSGoodsSkuModel *)skuModel{
    for (EJSSpecModel *specModel  in _selectSpcs) {
        EJSGoodsSpecModel *goodsSpecModel = _goodsModel.specs[[_selectSpcs indexOfObject:specModel]];
        if([specModel isKindOfClass:[EJSSpecModel class]]){
            if(![skuModel.specInfo containsString:[NSString stringWithFormat:@"%@:%@",goodsSpecModel.specName,specModel.value]]){
                return NO;
            }
        }else{
            return NO;
        }
    }
    return YES;
}




#pragma mark - Actions
- (IBAction)addToCartAction:(UIButton *)sender {
    if(!self.selectSkuModel){
        [[HUDHelper sharedInstance] tipMessage:@"请先选择规格属性"];
        return;
    }
    self.selectSkuModel.skuSelectCount = self.skuNumLabel.text.integerValue;
    if(_completion){
        _completion(self.selectSkuModel);
    }
    [self dismissAction:nil];
}

- (IBAction)dismissAction:(UIButton *)sender {
    [self removeFromSuperview];
}

- (IBAction)addAction:(UIButton *)sender {
    if(!self.selectSkuModel){
        [[HUDHelper sharedInstance] tipMessage:@"请先选择商品规格"];
        return;
    }
    NSInteger currentSelectCount = self.skuNumLabel.text.integerValue;
    if (currentSelectCount + self.goodsModel.minInCart.integerValue <= self.selectSkuModel.stock.integerValue){
        currentSelectCount  = currentSelectCount + self.goodsModel.minInCart.integerValue;
        self.skuNumLabel.text = @(currentSelectCount).stringValue;
    }else{
        [[HUDHelper sharedInstance] tipMessage:@"库存不足"];
        return;
    }
    
}

- (IBAction)subtractAction:(UIButton *)sender {
    if(!self.selectSkuModel){
        [[HUDHelper sharedInstance] tipMessage:@"请先选择商品规格"];
        return;
    }
    NSInteger currentSelectCount = self.skuNumLabel.text.integerValue;
    if (currentSelectCount - self.goodsModel.minInCart.integerValue >= self.goodsModel.minToBuy.integerValue){
        currentSelectCount = currentSelectCount - self.goodsModel.minInCart.integerValue;
    }else{
        [[HUDHelper sharedInstance] tipMessage:[NSString stringWithFormat:@"最小购买数量为%@",self.goodsModel.minToBuy]];
    }
    self.skuNumLabel.text = @(currentSelectCount).stringValue;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return _goodsModel.specs.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    EJSGoodsSpecModel *goodsSpecModel = _goodsModel.specs[section];
    return goodsSpecModel.specs.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSSpecCCell *ccell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EJSSpecCCell" forIndexPath:indexPath];
    EJSGoodsSpecModel *goodsSpecModel = _goodsModel.specs[indexPath.section];
    EJSSpecModel *model = goodsSpecModel.specs[indexPath.item];
    [ccell setSpceModel:model];
    return ccell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    EJSGoodsSpecModel *goodsSpecModel = _goodsModel.specs[indexPath.section];
    EJSSelectSpceCollectionReusableHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EJSSelectSpceCollectionReusableHeaderView" forIndexPath:indexPath];
    headerView.specTitleLabel.text = [NSString stringWithFormat:@"选择%@",goodsSpecModel.specName];
    
    return headerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat itemWidth = 50;
    CGFloat itemHeight = 50;
     EJSGoodsSpecModel *goodsSpecModel = _goodsModel.specs[indexPath.section];
    
    CGSize textSize = [goodsSpecModel.specName sizeWithFont:[UIFont systemFontOfSize:14.0] maxSize:CGSizeMake(ScreenWidth - 50, MAXFLOAT)];
    if(textSize.width + 30 > itemWidth){
        itemWidth = textSize.width + 30;
    }
    if(textSize.height + 30 > itemHeight){
        itemHeight = textSize.height + 30;
    }
    
    return CGSizeMake(itemWidth, itemHeight);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    EJSGoodsSpecModel *goodsSpecModel = _goodsModel.specs[section];
    NSString *headerTitle = [NSString stringWithFormat:@"选择%@",goodsSpecModel.specName];
    CGFloat itemHeight = 64;
    CGSize textSize = [headerTitle sizeWithFont:[UIFont systemFontOfSize:14.0] maxSize:CGSizeMake(ScreenWidth - 50, MAXFLOAT)];

    if(textSize.height + 50 > itemHeight){
        itemHeight = textSize.height + 50;
    }
    return CGSizeMake(ScreenWidth, itemHeight);
}

- (BOOL)collectionView:(UICollectionView *)collectionView canFocusItemAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EJSGoodsSpecModel *goodsSpecModel = _goodsModel.specs[indexPath.section];
    EJSSpecModel *model = goodsSpecModel.specs[indexPath.item];
    if(model.specSelectStatus == 0){
        [self.selectSpcs replaceObjectAtIndex:indexPath.section withObject:model];
    }else if (model.specSelectStatus == 1){
        [self.selectSpcs replaceObjectAtIndex:indexPath.section withObject:@""];
    }
    [self checkCanSelectGoodsSpceModel];
    [collectionView reloadData];
}


@end
